[JSON] Formatting XML into JSON

There are certain cases where you need to serialize some response into JSON but your desired API only offers XML res.

So here’s how you format/convert XML response into JSON.

First, There is no “one-to-one” relationship between XML and JSON.


  • Then, how to shove XML data into JSON object?

googling returned few ways to do this but you might want to do it as simple as possible

(i.e. online converters, XML → dict → JSON, … )


  • xmljson 0.2.0

    • supports converting XML ↔ JSON
    • available JSON conventions

      • Abdera: Use  for "attributes" for attributes,  "children" for nodes
      • BadgerFish: Use "$" for text content,  @ to prefix attributes
      • Cobra: Use "attributes" for sorted attributes (even when empty),  "children" for nodes, values are strings
      • GData: Use "$t" for text content, attributes added as-is
      • Parker: Use tail nodes for text content, ignore attributes
      • Yahoo : Use "content" for text content, attributes added as-is

Converting example using BadgerFish convention

XML

<employees>
    <person>
        <name value="Alice"/>
    </person>
    <person>
        <name value="Bob"/>
    </person>
</employees>

JSON

{
    "employees": [{
        "person": {
            "name": {
                "@value": "Alice"
            }
        }
    }, {
        "person": {
            "name": {
                "@value": "Bob"
            }
        }
    }]
}

  • In my case, I tried using Abdera first, result turned out with too many “attributes” and “children”
  • next tried Yahoo and looked great!

[example in Python]

pip install xmljson
from xmljson import yahoo

key = [API_SPECIFIC_KEY]
url = [API_URL] + key
request = requests.get(url).text
response = json.dumps(yahoo.data(fromstring(request)), ensure_ascii=False)
try:
    response = json.loads(response)['response']['body']
except KeyError:
    response = {
        'status_code': 200,
        'results': 'temporarily unavailable',
    }
serialized['STRUCTURE_0']['STRUCTURE_1'] = response

serialized = json.dumps(serialized)



Reference

https://pypi.org/project/xmljson/




ABOUT ME
I write codes and words.
제가 궁금하다면 ABOUT ME 버튼을 눌러보세요!

GitHubLinkedIn